package cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.synjones.minnovate.frame.basesdk.http.SynHttp;
import com.synjones.minnovate.frame.basesdk.http.SynSchedulersTranfs;
import com.synjones.minnovate.frame.basesdk.http.exception.AbsRxSubscriber;
import com.synjones.minnovate.frame.basesdk.http.exception.ApiException;
import com.synjones.minnovate.frame.basesdk.log.SynLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.mybean.mycontent;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.RecyclerBaseAdapter2;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.iapiserver.iapi;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.itemDecoration.AlphaDividerItemDecoration;

import static cn.ycbjie.ycaudioplayer.newpack.linkagescroll.config.MyConfig.baseURL;

//import com.example.linkagescroll.adapter.WebViewHolder;

/**
 * Created by shuyu on 2016/11/10.
 */

@SuppressLint("ValidFragment")
public class ListFragment3 extends Fragment {


    @BindView(R.id.list_item_recycler)
    XRecyclerView listItemRecycler;

    LinearLayoutManager linearLayoutManager;


    protected int devider;
    protected boolean isRefreshing;

    protected RecyclerBaseAdapter2 recyclerBaseAdapter2;
    protected List<mycontent> dataList = new ArrayList<>();
    protected SwipeRefreshLayout swipeRefreshLayout;
    private  String idss;

    @SuppressLint("ValidFragment")
    public ListFragment3(String ids) {
        super();
        idss = ids;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_list2, null);
        ButterKnife.bind(this, view);

        initView();

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public int getDevider() {
        return devider;
    }

    public void setDevider(int devider) {
        this.devider = devider;
    }

    private void initView() {

        linearLayoutManager = new LinearLayoutManager(getActivity());
        listItemRecycler.setLayoutManager(linearLayoutManager);
        listItemRecycler.addItemDecoration(new AlphaDividerItemDecoration(getDevider(), AlphaDividerItemDecoration.LIST));
        listItemRecycler.setPullRefreshEnabled(false);
        listItemRecycler.setLoadingMoreProgressStyle(ProgressStyle.SysProgress);

        resolveData();


//        listItemRecycler.setLoadingListener(new XRecyclerView.LoadingListener() {
//            @Override
//            public void onRefresh() {
//                //使用的是外部全局刷新
//            }
//
//            @Override
//            public void onLoadMore() {
//                if (isRefreshing())
//                    return;
//                setRefreshing(true);
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        setRefreshing(false);
//                        resolveData();
//                        listItemRecycler.loadMoreComplete();
//                    }
//                }, 2000);
//            }
//        });


    }

    private void getplayererlist(String id) {

        SynHttp.getInstance().getApi(baseURL, iapi.class).getContent(id)
                .compose(SynSchedulersTranfs.<mycontent>schedulersTransformer())
                .subscribe(new AbsRxSubscriber<mycontent>() {
                    @Override
                    public void onRxError(ApiException ex) {
                        SynLog.file(ex.getDisplayMessage());
                    }


                    public void onNext(mycontent mymycontent) {
                        dataList.add(mymycontent);
                        try {

                            if (recyclerBaseAdapter2 != null) {
                                recyclerBaseAdapter2.notifyDataSetChanged();
                            }
                            recyclerBaseAdapter2 = new RecyclerBaseAdapter2(getActivity(), dataList);
                            listItemRecycler.setAdapter(recyclerBaseAdapter2);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
//                            SynLog.file("String----->" + weatherInfoBean.toString());
                    }
                });

    }

//    private class RecyclerViewOnTouchListener implements View.OnTouchListener {
//
//        private int mLastY;
//        private int mCurrentY;
//
//        @Override
//        public boolean onTouch(View v, MotionEvent event) {
//            WebViewHolder webViewHolder = recyclerBaseAdapter2.getWebViewHolder();
//            if (webViewHolder == null) {
//                return false;
//            }
//            //获取WebView对象，以便将事件传递给他
//            WebView webView = (WebView) webViewHolder.itemView.findViewById(R.id.web_view);
//            //获取WebView所在item的顶部相对于其父控件（即RecyclerView的父控件）的距离
//            int itemViewTop = webViewHolder.itemView.getTop();
//            if (itemViewTop > 0) {
//                return false;
//            }
//            if (itemViewTop < 0) {
//                webViewHolder.itemView.scrollTo(0, 0);
//                return false;
//            }
//
//            //计算dy，用来判断滑动方向。dy<0-->向上滑动；dy>0-->向下滑动。
//            int dy = 0;
//            switch (event.getAction()) {
//                case MotionEvent.ACTION_DOWN:
//                    mLastY = (int) event.getY();
//                    break;
//                case MotionEvent.ACTION_MOVE:
//                    mCurrentY = (int) event.getY();
//                    dy = mCurrentY - mLastY;
//                    mLastY = mCurrentY;
//                    break;
//                case MotionEvent.ACTION_CANCEL:
//                case MotionEvent.ACTION_UP:
//                    dy = (int) (event.getY() - mLastY);
//                    mLastY = 0;
//                    mCurrentY = 0;
//                    break;
//            }
//            Log.d(TAG, "dy = " + dy);
//            Log.d(TAG, "itemViewTop = " + itemViewTop);
//
//            //如果WebView顶部距离其父控件距离未0，即WebView顶部滑动到RecyclerView父控件顶部重合时，
//            // 此时需要拦截滑动事件交给WebView处理。
//            if (itemViewTop == 0) {
//                if (shouldIntercept(webView, dy)) {
//                    webView.onTouchEvent(event);
//                    return true;
//                }
//            }
//            return false;
//        }
//
//        /**
//         * 是否拦截滑动事件，判断的逻辑是：<br/>
//         * 1,如果是向上滑动，并且webview能够向上滑动，则拦截事件；<br/>
//         * 2,如果是向下滑动，并且webview能够向下滑动，则拦截事件。
//         *
//         * @param view 判断能够滑动的view
//         * @param dy   滑动间距
//         * @return true拦截，false不拦截。
//         */
//        private boolean shouldIntercept(View view, int dy) {
//            //canScrollVertically方法的第二个参数direction，传1时返回是否能够向上滑动，传-1时返回能否向下滑动。
//            //dy<0-->向上滑动；dy>0-->向下滑动。
//            boolean scrollUp = dy < 0 && ViewCompat.canScrollVertically(view, 1);
//            boolean scrollDown = dy > 0 && ViewCompat.canScrollVertically(view, -1);
//            return scrollUp || scrollDown || dy == 0;
//        }
//    }

    private void resolveData() {

        getplayererlist(idss);

//        for (int i = 0; i < 1; i++) {
//            RecyclerDataModel recyclerDataModel = new RecyclerDataModel();
//            dataList.add(recyclerDataModel);
//        }

    }

    /**
     * 刷新
     */
    public void refresh() {
        if (isRefreshing())
            return;
        setRefreshing(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setRefreshing(false);
                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
                dataList.clear();
                resolveData();
            }
        }, 2000);
    }

    /**
     * 回到顶部
     */
    public void changeToTop() {
        listItemRecycler.stopNestedScroll();
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.scrollToPosition(0);
    }

    public boolean isRefreshing() {
        return isRefreshing;
    }

    public void setRefreshing(boolean refreshing) {
        isRefreshing = refreshing;
    }

    public void setSwipeRefreshLayout(SwipeRefreshLayout swipeRefreshLayout) {
        this.swipeRefreshLayout = swipeRefreshLayout;
    }

    public RecyclerView getScrollableView() {
        return listItemRecycler;
    }

}
